package com.ruoyi.system.controller;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.SysBusinessInfoMapper;
import com.ruoyi.system.mapper.SysDealerInfoMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.system.domain.SysBusinessInfo;
import com.ruoyi.system.service.ISysBusinessInfoService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 新建订单
 * 
 * @author ruoyi
 * @date 2021-08-10
 */
@Api(value = "订单管理")
@RestController
@RequestMapping("sysBusinessInfo")
public class SysBusinessInfoController extends BaseController
{
	
	@Autowired
	private ISysBusinessInfoService sysBusinessInfoService;

	@Resource
	private SysBusinessInfoMapper sysBusinessInfoMapper;
	@Resource
	private SysUserMapper sysUserMapper;
	@Resource
	private SysDeptMapper sysDeptMapper;
	@Resource
	private SysDealerInfoMapper sysDealerInfoMapper;
	
	/**
	 * 查询${tableComment}
	 */
	@ApiOperation(value = "根据id查询")
	@ApiImplicitParam(name = "id", value = "id", required = true)
	@GetMapping("get/{id}")
	public SysBusinessInfo get(@PathVariable("id") Long id)
	{
		return sysBusinessInfoService.selectSysBusinessInfoById(id);
		
	}
	
	/**
	 * 查询新建订单列表
	 */
	@ApiOperation(value = "查询新建订单列表及根据条件查询列表")
	@GetMapping("list")
	public R list(SysBusinessInfo sysBusinessInfo,HttpServletRequest request)
	{
		Long userId = Long.valueOf(request.getHeader(Constants.CURRENT_ID));
		sysBusinessInfo.setCreateBy(String.valueOf(userId));
		startPage();
        return result(sysBusinessInfoService.selectSysBusinessInfoList(sysBusinessInfo));
	}

	/**
	 * 查询新建订单列表
	 */
	@ApiOperation(value = "查询未完成订单列表")
	@GetMapping("unList")
	public R list(HttpServletRequest request)
	{
		Long userId = Long.valueOf(request.getHeader(Constants.CURRENT_ID));
		startPage();
		return result(sysBusinessInfoService.selectUnList(String.valueOf(userId)));
	}

	@ApiOperation(value = "生成订单号等信息")
	@PostMapping("insertOrderId")
	public R insertOrderId(HttpServletRequest request)
	{
		List<SysBusinessInfo> list = new ArrayList<>();
		SysBusinessInfo sysBusinessInfo = new SysBusinessInfo();
		// 获取用户ID
		Long userId = Long.valueOf(request.getHeader(Constants.CURRENT_ID));
		sysBusinessInfo.setCreateBy(String.valueOf(userId));
		SysUser sysUser = sysUserMapper.selectUserById(userId);
		String organCode = "";
		String dealerName = "";
		if(null != sysUser){
			SysDept sysDept = sysDeptMapper.selectDeptById(sysUser.getDeptId());
			if(null != sysDept){
				dealerName = sysDept.getDeptName();
				organCode = sysDealerInfoMapper.selectOrganCodeByDealerName(dealerName);
			}
		}

		SimpleDateFormat sdf=new SimpleDateFormat("yyyy");
		String orderId = "YTZ100"+ organCode +sdf.format(new Date())+"A00001";
		String orderIdb = "YTZ100"+ organCode +sdf.format(new Date())+"B00001";
		String orderIdc = "YTZ100"+ organCode +sdf.format(new Date())+"C00001";
		String orderIdd = "YTZ100"+ organCode +sdf.format(new Date())+"D00001";
		String orderIde = "YTZ100"+ organCode +sdf.format(new Date())+"E00001";
		String orderIdf = "YTZ100"+ organCode +sdf.format(new Date())+"F00001";
		String orderIdg = "YTZ100"+ organCode +sdf.format(new Date())+"G00001";
		String orderIdh = "YTZ100"+ organCode +sdf.format(new Date())+"H00001";
		String orderIdi = "YTZ100"+ organCode +sdf.format(new Date())+"I00001";
		String orderIdj = "YTZ100"+ organCode +sdf.format(new Date())+"J00001";
		String orderIdk = "YTZ100"+ organCode +sdf.format(new Date())+"K00001";
		String orderIdl = "YTZ100"+ organCode +sdf.format(new Date())+"L00001";
		String orderIdm = "YTZ100"+ organCode +sdf.format(new Date())+"M00001";
		String orderIdn = "YTZ100"+ organCode +sdf.format(new Date())+"N00001";
		String orderIdo = "YTZ100"+ organCode +sdf.format(new Date())+"O00001";
		String orderIdp = "YTZ100"+ organCode +sdf.format(new Date())+"P00001";
		String orderIdq = "YTZ100"+ organCode +sdf.format(new Date())+"Q00001";
		String orderIdr = "YTZ100"+ organCode +sdf.format(new Date())+"R00001";
		String orderIds = "YTZ100"+ organCode +sdf.format(new Date())+"S00001";
		String orderIdt = "YTZ100"+ organCode +sdf.format(new Date())+"T00001";
		String orderIdu = "YTZ100"+ organCode +sdf.format(new Date())+"U00001";
		String orderIdv = "YTZ100"+ organCode +sdf.format(new Date())+"V00001";
		String orderIdw = "YTZ100"+ organCode +sdf.format(new Date())+"W00001";
		String orderIdx = "YTZ100"+ organCode +sdf.format(new Date())+"X00001";
		String orderIdy = "YTZ100"+ organCode +sdf.format(new Date())+"Y00001";
		String orderIdz = "YTZ100"+ organCode +sdf.format(new Date())+"Z00001";

		int num = sysBusinessInfoMapper.selectNum();
		if(0 == num){
			sysBusinessInfo.setOrderId(orderId);
		}else {
			String newestOrderId = sysBusinessInfoMapper.selectNewestOrderId();

			if("A99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdb);
			}else if("B99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdc);
			}else if("C99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdd);
			}else if("D99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIde);
			}else if("E99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdf);
			}else if("F99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdg);
			}else if("G99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdh);
			}else if("H99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdi);
			}else if("I99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdj);
			}else if("J99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdk);
			}else if("K99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdl);
			}else if("L99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdm);
			}else if("M99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdn);
			}else if("N99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdo);
			}else if("O99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdp);
			}else if("P99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdq);
			}else if("Q99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdr);
			}else if("R99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIds);
			}else if("S99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdt);
			}else if("T99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdu);
			}else if("U99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdv);
			}else if("V99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdw);
			}else if("W99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdx);
			}else if("X99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdy);
			}else if("Y99999".equals(newestOrderId.substring(16,21))){
				sysBusinessInfo.setOrderId(orderIdz);
			}

			int b=Integer.valueOf(newestOrderId.substring(17,21));
			String c = String.format("%05d", b + 1);
			sysBusinessInfo.setOrderId("YTZ100"+ organCode +sdf.format(new Date()) + newestOrderId.substring(15,16) + c);
		}

		sysBusinessInfo.setOrderTime(DateUtils.getNowDate());
		sysBusinessInfo.setOrganCode(organCode);
		sysBusinessInfo.setDealerName(dealerName);

		// 机构编码+mm/dd+0001
		SimpleDateFormat df=new SimpleDateFormat("MMdd");
		String newestServiceContractNo = sysBusinessInfoMapper.selectNewestServiceContractNo();
		if(StringUtils.isEmpty(newestServiceContractNo)){
			sysBusinessInfo.setServiceContractNo(organCode + df.format(new Date()) + String.format("%04d",1));
		}else {
			if(df.format(new Date()).equals(newestServiceContractNo.substring(5,9))){
				sysBusinessInfo.setServiceContractNo(organCode + df.format(new Date()) + String.format("%04d", Integer.valueOf(newestServiceContractNo.substring(9,13)) + 1));
			}else {
				sysBusinessInfo.setServiceContractNo(organCode + df.format(new Date()) + String.format("%04d",1));
			}
		}

		sysBusinessInfo.setAgreement("0");
		sysBusinessInfoService.insertSysBusinessInfo(sysBusinessInfo);

		list.add(sysBusinessInfo);
		return result(list);
	}
	/**
	 * 新增保存新建订单
	 */
//	@PostMapping("save")
//	public R addSave(@RequestBody SysBusinessInfo sysBusinessInfo)
//	{
//		if(!StringUtils.isEmpty(sysBusinessInfo.getInsuranceStartdate())){
//			try{
//				SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
//				Calendar cd=Calendar.getInstance();
//				try{
//					cd.setTime(df.parse(df.format(new Date())));
//				}catch(ParseException e){
//					e.printStackTrace();
//				}
//
//				cd.add(Calendar.YEAR,1);
//
//				// 当创建日期与商业险起保日期不一致时，弹出提示“请准备验车照片”
//				if(!df.format(sysBusinessInfo.getOrderTime()).equals(df.format(sysBusinessInfo.getInsuranceStartdate()))){
//					return toAjaxError(400,"请准备验车照片");
//				}
//				// 当商业险起保日期大于一年的，则提示“商业险已脱保，不符合投保条件”，需要重新输入
//
//				if(sysBusinessInfo.getInsuranceStartdate().compareTo(cd.getTime()) > 0){
//					return toAjaxError(400,"商业险已脱保，不符合投保条件");
//				}
//
//			}catch (Exception e){
//
//			}
//		}
//
//		if(!StringUtils.isEmpty(sysBusinessInfo.getInsuredAmount())){
//			BigDecimal result = new BigDecimal(sysBusinessInfo.getInsuredAmount()).multiply(new BigDecimal("0.15"));
//			sysBusinessInfo.setCompensationLimit(result.toString());
//		}
//
//		if(!StringUtils.isEmpty(sysBusinessInfo.getCarNumber())){
//			sysBusinessInfo.setCarNumber(sysBusinessInfo.getCarNumber().toUpperCase());
//		}
//
//		if(!StringUtils.isEmpty(sysBusinessInfo.getVinNo())){
//			sysBusinessInfo.setVinNo(sysBusinessInfo.getVinNo().toUpperCase());
//		}
//
//		if(!StringUtils.isEmpty(sysBusinessInfo.getEngineNo())){
//			sysBusinessInfo.setEngineNo(sysBusinessInfo.getEngineNo().toUpperCase());
//		}
//
//		return toAjax(sysBusinessInfoService.insertSysBusinessInfo(sysBusinessInfo));
//	}

	/**
	 * 修改保存新建订单
	 */
	@ApiOperation(value = "修改保存新建订单")
	@PostMapping("update")
	public R editSave(@RequestBody SysBusinessInfo sysBusinessInfo)
	{
		if(!StringUtils.isEmpty(sysBusinessInfo.getInsuranceStartdate())){
			try{
				SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
				Calendar cd=Calendar.getInstance();
				try{
					cd.setTime(df.parse(df.format(new Date())));
				}catch(ParseException e){
					e.printStackTrace();
				}

				cd.add(Calendar.YEAR,1);

				// 当商业险起保日期大于一年的，则提示“商业险已脱保，不符合投保条件”，需要重新输入
				if(sysBusinessInfo.getInsuranceStartdate().compareTo(cd.getTime()) > 0){
					return toAjaxError(400,"商业险已脱保，不符合投保条件");
				}

			}catch (Exception e){

			}
		}

		if(!StringUtils.isEmpty(sysBusinessInfo.getInsuredAmount())){
			BigDecimal result = new BigDecimal(sysBusinessInfo.getInsuredAmount()).multiply(new BigDecimal("0.15"));
			sysBusinessInfo.setCompensationLimit(result.toString());
		}

		if(!StringUtils.isEmpty(sysBusinessInfo.getCarNumber())){
			sysBusinessInfo.setCarNumber(sysBusinessInfo.getCarNumber().toUpperCase());
		}

		if(!StringUtils.isEmpty(sysBusinessInfo.getVinNo())){
			sysBusinessInfo.setVinNo(sysBusinessInfo.getVinNo().toUpperCase());
		}

		return toAjax(sysBusinessInfoService.updateSysBusinessInfo(sysBusinessInfo));
	}

	/**
	 * 确认点击协议
	 */
	@ApiImplicitParam(name = "id", value = "id", required = true)
	@ApiOperation(value = "确认点击协议")
	@PostMapping("updateAgreement/{id}")
	public R updateAgreement(@PathVariable("id") Long id)
	{
		return toAjax(sysBusinessInfoService.updateAgreement(id));
	}

	/**
	 * 确认完成订单
	 */
	@ApiImplicitParam(name = "id", value = "id", required = true)
	@ApiOperation(value = "确认完成订单")
	@PostMapping("updateStatus/{id}")
	public R updateStatus(@PathVariable("id") Long id)
	{
		return toAjax(sysBusinessInfoService.updateStatus(id));
	}
	
	/**
	 * 删除${tableComment}
	 */
	@ApiImplicitParam(name = "ids", value = "ids", required = true)
	@ApiOperation(value = "删除")
	@PostMapping("remove/{id}")
	public R remove(@PathVariable("id") Long id)
	{		
		return toAjax(sysBusinessInfoService.deleteSysBusinessInfoById(id));
	}

}
